package cn.shanke.torrentmanagerserver.util;

import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    public static void createLink(String source, String target) throws IOException{
        Path sourceFile = Paths.get(source);
        Path targetFile = Paths.get(target);

        if (!Files.exists(targetFile.getParent())) {
            Files.createDirectories(targetFile.getParent());
        }
        Files.createLink(targetFile, sourceFile);
    }

    public static void moveTo(String source, String target) throws IOException{
        Path sourceFile = Paths.get(source);
        Path targetFile = Paths.get(target);

        if (!Files.exists(targetFile.getParent())) {
            Files.createDirectories(targetFile.getParent());
        }
        Files.move(sourceFile, targetFile);
    }

    public static void chown(String path, String user) throws IOException{
        Path file = Paths.get(path);
        System.out.println(Files.getFileAttributeView(file, PosixFileAttributeView.class).readAttributes().owner().getName());
        System.out.println(Files.getFileAttributeView(file, PosixFileAttributeView.class).readAttributes().group().getName());
        UserPrincipal userPrincipal = file.getFileSystem().getUserPrincipalLookupService().lookupPrincipalByName(user);
        Files.setOwner(file, userPrincipal);
        System.out.println(Files.getFileAttributeView(file, PosixFileAttributeView.class).readAttributes().owner().getName());
        System.out.println(Files.getFileAttributeView(file, PosixFileAttributeView.class).readAttributes().group().getName());
    }

    public static List<String> readAllLines(InputStream inputStream){
        List<String> lines = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        try {
            while ((line = reader.readLine())!=null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(reader);
        }
        return lines;
    }

//    public static void main(String[] args) throws IOException {
//        chown("/Users/shanke/Documents/appdata/torrentmanager/Season 1/mwzz1.png", "99");
//    }
}
